/*
 * Copyright (c) 2014, Asiainfo-Linkage. All rights reserved.
 * Asiainfo-Linkage PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package edu.w106.platform.scheduler.job;

import java.util.ArrayList;
import java.util.List;

import au.id.jericho.lib.html.Element;
import au.id.jericho.lib.html.HTMLElementName;
import au.id.jericho.lib.html.Source;
import edu.w106.platform.http.HttpGetUtils;
import edu.w106.platform.http.Response;
import edu.w106.platform.mc.Message;
import edu.w106.platform.mc.TrayMessage;
import edu.w106.platform.scheduler.AbsJob;

/**
 * <p><b>标题：</b>CERTMonitorJob.</p>
 *
 * <p><b>描述：监控国家互联网应急中旬发布的最新漏洞.</b></p>
 *
 * <p><b>版权：</b>Copyright (c) 2014 亚信联创</p>
 *
 * <p><b>工程：</b>platform-mc</p>
 *
 * @author w106
 *
 * @version 1.0.0
 *
 * @since 2014-5-5 下午1:48:46
 */
public class CERTMonitorJob extends AbsJob {

    /* (non-Javadoc)
     * @see edu.w106.platform.scheduler.AbsJob#executeJob(java.lang.String)
     */
    @Override
    protected void executeJob(String config) {
        HttpGetUtils get = new HttpGetUtils();
        Response resp = get.sendRequest(config);
        if (resp.getStatus() == 304) {
            TrayMessage.getInstance().addMessage(new Message(Message.MSG_INFO, "今日无国家互联网应急中心无漏洞发布"));
            return;
        } else if (resp.getStatus() == Response.HTTP_ERROR) {
            TrayMessage.getInstance().addMessage(
                    new Message(Message.MSG_WARN, "检查国家互联网应急中心漏洞发生错误:" + resp.getResponse()));
            return;
        }
        Response cache = get.getCacheReponse();
        List<String> newInfo = getNewSecurityBulletins(cache, resp);
        for (String str : newInfo) {
            TrayMessage.getInstance().addMessage(new Message(Message.MSG_WARN, "查国家互联网应急中心最新漏洞发布:" + str));
        }

    }

    private List<String> getNewSecurityBulletins(Response cache, Response newpage) {
        List<String> res = new ArrayList<String>();
        List<String> cacheBulletins = getPageInfo(cache);
        List<String> pageBulletins = getPageInfo(newpage);
        for (String bull : pageBulletins) {
            if (!cacheBulletins.contains(bull)) {
                res.add(bull);
            }
        }
        return res;
    }

    private List<String> getPageInfo(Response page) {

        List<String> bulletions = new ArrayList<String>();
        if (page == null) {
            return bulletions;
        }
        Source source = new Source(page.getResponse());
        List<Element> uls = source.findAllElements(HTMLElementName.UL);
        for (Element ul : uls) {
            if ("waring_con".equals(ul.getAttributeValue("class"))) {
                List<Element> lis = ul.findAllElements(HTMLElementName.LI);
                for (Element elli : lis) {
                    bulletions.add(elli.getTextExtractor().toString());
                }
            }
        }
        return bulletions;
    }
}
